<?php

namespace App\Controller\Api\User;

use App\Controller\Api\BaseController;
use App\Model\ConfusionCategory;
use App\Model\ConsultantAuthenticationType;
use App\Model\ConsultantType;
use App\Model\Country;
use App\Model\Language;
use App\Model\Policy;
use App\Model\QuestionnaireAnswer;
use App\Model\QuestionnaireQuestion;
use App\Model\QuestionnaireUserResult;
use App\Model\ReportType;
use App\Model\SearchHotlist;
use App\Model\SysBanner;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;


/**
 * @Controller(prefix="/user/v1/common")
 */
class CommonController extends BaseController
{


    /**
     * 国家列表
     * 缓存--countryList
     * @RequestMapping(path="countryList")
     */
    public function countryList()
    {

        $countryList = cache()->get('countryList');

        if (is_null($countryList)) {

            $countryList = Country::where(['pid' => 0])->select(['id', 'self_name as name', 'code', 'code3'])->get()->toArray();
            cache()->set('countryList', $countryList);

        }

        return $this->response->returnSuccess(['list' => $countryList]);

    }


    /**
     * 语言列表
     * 缓存--languageList
     * @RequestMapping(path="languageList")
     * @return ResponseInterface
     * @throws InvalidArgumentException
     */
    public function languageList()
    {

        $languageList = cache()->get('languageList');

        if (is_null($languageList)) {
            $languageList = Language::get()->toArray();
            cache()->set('languageList', $languageList);
        }

        return $this->response->returnSuccess(['list' => $languageList]);

    }


    /**
     * 政策信息 1 关于我们  2 隐私政策
     * @RequestMapping(path="policy")
     * @return ResponseInterface
     */
    public function policy()
    {

        $type = $this->request->query('type', 1);

        $info = Policy::find($type);

        return $this->response->returnSuccess($info->toArray());

    }


    /**
     * 困惑列表
     * 缓存--confusionCategoryList:
     * @RequestMapping(path="confusionCategoryList")
     * @return ResponseInterface
     * @throws InvalidArgumentException
     */
    public function confusionCategoryList()
    {

        $lang = getLang();
        $cacheKey = 'confusionCategoryList:' . $lang;


        $confusionCategoryList = cache()->get($cacheKey);
        if (is_null($confusionCategoryList)) {
            $confusionCategoryList = ConfusionCategory::where(['pid' => 0, 'status' => 1, 'lang' => $lang])->get()->toArray();
            if (!empty($confusionCategoryList)) {
                cache()->set($cacheKey, $confusionCategoryList);
            }
        }
        return $this->response->returnSuccess(['list' => $confusionCategoryList]);

    }


    /**
     * @RequestMapping(path="homeBanner")
     * @return ResponseInterface
     * @throws InvalidArgumentException
     */
    public function homeBanner()
    {

        $lang = getLang();
        $cacheKey = 'homeBanner:' . $lang;

        $homeBanner = cache()->get($cacheKey);
        if (is_null($homeBanner)) {
            $homeBanner = SysBanner::where(['status' => 1])->orderBy('sort', 'desc')->get()->toArray();

            if (!empty($homeBanner)) {
                cache()->set($cacheKey, $homeBanner);
            }
        }

        return $this->response->returnSuccess(['list' => $homeBanner]);

    }


    /**
     * 搜索热词榜
     * @RequestMapping(path="popularSearchesList")
     * @return ResponseInterface
     * @throws InvalidArgumentException
     */
    public function popularSearchesList()
    {

        $lang = getLang();
        $cacheKey = 'popularSearchesList:' . $lang;
        $popularSearchesList = cache()->get($cacheKey);
        if (is_null($popularSearchesList)) {
            $popularSearchesList = SearchHotlist::where(['status' => 1, 'lang' => $lang])->select(['keyword'])->orderBy('search_count', 'desc')->limit(9)->get()->toArray();
            if (!empty($popularSearchesList)) {
                cache()->set($cacheKey, $popularSearchesList, 3600);
            }
        }

        return $this->response->returnSuccess(['list' => $popularSearchesList]);
    }


    /**
     * 初始化接口 包含基本信息
     * @RequestMapping(path="initInfo")
     */
    public function initInfo()
    {

        $md5Kkey = env('MD5_KEY', 'Nbef8NfqWE4embWO');

        $timestamp = $this->request->header('timestamp', '');


        $sign = $this->request->query('sign');

        $checkSign = md5($md5Kkey . $timestamp);


        if ($sign != $checkSign) {
            return $this->response->returnFail();
        }


        $policy = Policy::getPolicy();
        $data['policy'] = $policy;

        $data['hx'] = [
            'appKey' => env('HX_APP_KEY', '1171230214166361#seekingdev'),
            'clientId' => env('HX_CLIENT_ID', 'YXA6pLiJODEASniMD6Bu1X8NfA'),
            'prefix' => 'zx'
        ];

        $data['version'] = [
            'versionId' => 1,
            'version' => '1.0.0'
        ];

        $data['downloadUrl'] = 'https://www.badiu.com';

        $data['share'] = [
            'url' => 'https://www.baidu.com',
            'title' => '分享标题',
            'message' => 'message'
        ];

        $data['agora'] = [
          'appId' =>env('AGORA_APPID','d00be774b41b4ab7a12dd2be282e5f44'),
          'appCertificate' =>env('AGORA_CERTIFICATE','036fbee15812471084b0e63d72c1104b'),
        ];


        return $this->response->returnSuccess($data);

    }


    /**
     * @RequestMapping(path="registerQuestion")
     */
    public function registerQuestion()
    {

        $aid = $this->request->query('aid', 0);


        $lang = getLang();
        $questionSelect = [
            'id',
            'aid',
            "content_{$lang} as content"
        ];
        $question = QuestionnaireQuestion::where(['aid' => $aid])->select($questionSelect)->first();

        if ($question) {
            $question = $question->toArray();
        }

        $answerSelect = [
            'id',
            'qid',
            "content_{$lang} as content"
        ];
        $answer = QuestionnaireAnswer::where(['qid' => $question['id']])->select($answerSelect)->get()->toArray();

        //开始答题了
        if ($aid != 0) {
            $answerSelect = [
                'id',
                'qid',
                "content_{$lang} as content"
            ];
            $userAnswerResult = QuestionnaireAnswer::where(['id' => $aid])->select($answerSelect)->first();

            $userQuestion = QuestionnaireQuestion::where(['id' => $userAnswerResult['qid']])->select($questionSelect)->first();

            $userAnswer = [
                'uid' => $this->uid(),
                'qid' => $userQuestion['id'],
                'aid' => $aid,
                'quest' => $userQuestion['content'],
                'answer' => $userAnswerResult['content'] ?? '',
                'create_time' => time()
            ];
            QuestionnaireUserResult::insert($userAnswer);
        }

        return $this->response->returnSuccess(['num'=>3,'question' => $question, 'answer' => $answer]);


    }


    /**
     * @RequestMapping(path="reportTypeList")
     * @return ResponseInterface
     * @throws InvalidArgumentException
     */
    public function reportTypeList()
    {


        $type = $this->request->query('type', 1);

        $lang = getLang();
        $cacheKey = 'reportTypeList:' . $type . ':' . $lang;

        $reportTypeList = cache()->get($cacheKey);
        if (is_null($reportTypeList)) {
            $reportTypeList = ReportType::where(['lang' => $lang])->orderByDesc('sort')->get()->toArray();
            if (!empty($reportTypeList)) {
                cache()->set($cacheKey, $reportTypeList);
            } else {
                $reportTypeList = null;
            }
        }

        return $this->response->returnSuccess(['list' => $reportTypeList]);


    }



    /**
     * @RequestMapping(path="consultantTypeList")
     * @return ResponseInterface
     */
    public function consultantTypeList()
    {

        $lang = getLang();


        $list = ConsultantType::from('consultant_type as a')
            ->leftJoin('consultant_authentication_type as b','a.id','=','b.user_type')
            ->select(['a.id','a.icon','b.name'])
            ->orderByDesc('sort')->get()->toArray();

        return $this->response->returnSuccess(['list' => $list]);

    }



}
